<?php

namespace App\Jobs\Controller;

use App\Jobs\BaseJob;
use App\Models\LogCount;
use Illuminate\Support\Facades\DB;

class LogCounterJob extends BaseJob
{
    /**
     * @param $msgContent
     * @return bool
     */
    public function create($msgContent)
    {
        $this->createLogCounterTable($msgContent['msgContent']['created_at']);
        service()->LogCountService->createLog($msgContent['msgContent']);

        return true;
    }

    /**
     * 创建[log_counter_当前年当前季度]表
     * 先验证表是否存在，不存在则创建
     * @param $time [时间戳]
     * @return bool
     */
    private function createLogCounterTable($time)
    {
        $newTableName = LogCount::getTableNameBySeason($time);
        $tables = DB::select('show tables like "log_count_%"');
        $tableArr = [];
        foreach ($tables as $tableInfo) {
            foreach ($tableInfo as $dbName => $tableName) {
                $tableArr[] = $tableName;
            }
        }
        if (!in_array($newTableName, $tableArr)) {
            $sql = "CREATE TABLE `" . $newTableName . "` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增长ID',
  `send_user_id` char(24) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '动作发起用户ID',
  `receive_user_id` char(24) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '动作接收用户ID',
  `target_id` char(24) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '动作的主体ID，如用户评论后，此评论的主体',
  `target_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '动作的主体类型：1文章，2笔记，3评论，4回复，5动态，6收藏夹',
  `action_id` char(24) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '动作的ID，如用户评论后产生的ID',
  `action_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '看文档【V2值域】',
  `created_at` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳',
  PRIMARY KEY (`id`),
  KEY `idx_send_user_id` (`send_user_id`) USING BTREE,
  KEY `idx_receive_user_id` (`receive_user_id`) USING BTREE,
  KEY `idx_target_id` (`target_id`) USING BTREE,
  KEY `idx_target_type` (`target_type`) USING BTREE,
  KEY `idx_action_type` (`action_type`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='<日志>统计日志表';";
            DB::statement($sql);
        }
        return true;
    }

}
